<template>
  <div>
    <div class="top-panel">
      <el-card>
        <el-form
          ref="searchForm"
          :model="searchForm"
          label-width="80px"
          label-position="right"
        >
          <el-row>
            <el-col :span="5">
              <el-form-item size="small" label="角色名称">
                <el-input
                  class="password-input"
                  v-model="searchForm.roleNameFuzzy"
                  clearable
                  placeholder="输入工号或姓名"
                  @keyup.enter.native="loadDataList"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item size="small" label="描述">
                <el-input
                  class="password-input"
                  v-model="searchForm.roleDescFuzzy"
                  clearable
                  placeholder="支持模糊搜索"
                  @keyup.enter.native="loadDataList"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col
              :span="4"
              :style="{ paddingLeft: '10px', 'padding-top': '3px' }"
            >
              <el-button type="success" size="mini" @click="loadDataList()"
                >查询</el-button
              >
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-button
                type="primary"
                size="mini"
                @click="showEdit(null, 'add')"
                >新增角色</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <el-row :gutter="20">
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>角色列表</span>
          </div>
          <Table
            ref="dataTable"
            :columns="columns"
            :fetch="loadDataList"
            :dataSource="tableData"
            :options="tableOptions"
            @row-click="rowClick"
          >
          </Table>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>菜单信息</span>
            <el-button
              type="primary"
              size="mini"
              :style="{ float: 'right' }"
              :disabled="this.selectedMenuIds.length === 0"
              @click="saveRoleMenu"
              >保存</el-button
            >
          </div>
          <div class="detail-tree-panel">
            <el-tree
              size="small"
              ref="menu-tree-detail"
              node-key="menuId"
              show-checkbox
              :data="treeData"
              default-expand-all
              v-if="treeData.length"
              :props="replaceFields"
              @check-change="checkTreeMenu"
              check-strictly
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <Dialog
      ref="editDialog"
      :title="editDialogInfo.title"
      :buttons="editDialogInfo.buttons"
      :visible="editDialogInfo.show"
      @close="editDialogInfo.show = false"
    >
      <el-form
        ref="editForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName" size="small">
          <el-input :maxLength="20" v-model="formData.roleName" />
        </el-form-item>
        <el-form-item label="关联菜单" prop="menuIds" size="small">
          <div class="tree-panel">
            <el-tree
              size="small"
              ref="menu-tree"
              node-key="menuId"
              show-checkbox
              v-model="formData.menuIds"
              :data="treeData"
              default-expand-all
              v-if="treeData.length"
              :props="replaceFields"
              check-strictly
              @check-change="checkTree"
            />
          </div>
        </el-form-item>
        <el-form-item label="角色描述" size="small">
          <el-input
            type="textarea"
            :maxLength="250"
            v-model="formData.roleDesc"
          />
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      permissionCode: {
        edit: 'settings_role_edit',
        del: 'settings_role_del',
      },
      api: {
        loadRole: '/settings/loadRoles',
        loadMenu: '/settings/menuList',
        saveRole: '/settings/saveRole',
        saveRoleMenu: '/settings/saveRoleMenu',
        roleDetail: '/settings/getRoleByRoleId',
        delRole: '/settings/delRole',
      },
      tableData: {},
      tableOptions: {
        topHeight: 146,
      },
      columns: [
        {
          label: '角色名称',
          prop: 'roleName',
        },
        {
          label: '描述',
          prop: 'roleDesc',
        },
        {
          label: '创建时间',
          prop: 'createTime',
        },
        {
          label: '操作',
          prop: 'operation',
          width: 120,
          render: (row, index) => {
            return (
              <div class="table-list-op-btns">
                <span v-has={this.permissionCode.edit}>
                  <a
                    href="javascript:void(0)"
                    onClick={(e) => this.showEdit(e, 'edit', row)}
                  >
                    编辑
                  </a>
                </span>
                <span v-has={this.permissionCode.del}>
                  <a
                    href="javascript:void(0)"
                    onClick={(e) => this.delRole(e, row)}
                  >
                    删除
                  </a>
                </span>
              </div>
            )
          },
        },
      ],
      editDialogInfo: {
        show: false,
        title: '新增角色',
        buttons: [
          {
            type: 'primary',
            text: '确定',
            click: (e) => {
              this.submitForm(e)
            },
          },
        ],
      },
      formData: {
        pId: 0,
        sort: 0,
      },
      //菜单
      treeData: [],
      //菜单树形匹配
      replaceFields: {
        label: 'menuName',
        id: 'menuId',
      },
      rules: {
        roleName: [{ required: true, message: '请输入角色名称' }],
        menuIds: [
          { required: true, message: '请选择菜单', trigger: ['change'] },
        ],
      },
      selectedMenuIds: [],
      curRow: {},
      searchForm: {},
    }
  },
  methods: {
    //加载菜单列表
    async loadDataList() {
      let params = {
        pageNo: this.tableData.pageNo,
        pageSize: this.tableData.pageSize,
      }
      Object.assign(params, this.searchForm)
      let result = await this.Request({
        url: this.api.loadRole,
        params: params,
      })
      this.tableData = result

      let row = undefined
      if (this.curRowData !== undefined) {
        row = result.list.find((item) => {
          return item.payChannelId == this.curRowData.payChannelId
        })
      }
      if (row == undefined) {
        row = result.list.length > 0 ? result.list[0] : undefined
      }

      if (row != undefined) {
        this.$refs.dataTable.setCurrentRow(row)
        this.rowClick(row)
      } else {
        this.$refs['menu-tree-detail'].setCheckedKeys([])
      }
    },
    //提交
    async submitForm(e) {
      e.preventDefault()
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) {
          return false
        }
        let menuIds = ''
        if (this.formData.menuIds instanceof Array) {
          menuIds = this.formData.menuIds.join(',')
        } else if (this.formData.menuIds instanceof Object) {
          menuIds = this.formData.menuIds.checked.join(',')
        }
        let params = {
          roleId: this.formData.roleId,
          roleName: this.formData.roleName,
          roleDesc: this.formData.roleDesc,
          menuIds: menuIds,
        }
        await this.Request({
          url: this.api.saveRole,
          params: params,
        })
        this.$refs.editDialog.close()
        this.$message.success('保存成功')
        this.loadDataList()
      })
    },
    //详情
    //编辑
    async showEdit(e, type, data) {
      if (e) {
        e.stopPropagation()
      }
      // this.$refs.editForm.resetFields()
      this.editDialogInfo.show = true
      if (this.$refs['menu-tree']) {
        this.$refs['menu-tree'].setCheckedKeys([])
      }
      this.$nextTick(async () => {
        if (this.$refs['editForm']) {
          this.$refs['editForm'].resetFields()
        }
        this.editDialogInfo.buttons[0].text = '确定'
        if (type === 'add') {
          this.editDialogInfo.title = '新增角色'
          this.formData = {
            menuIds: [],
          }
        } else {
          if (type === 'edit') {
            this.editDialogInfo.title = '修改角色'
          } else if (type === 'detail') {
            this.editDialogInfo.buttons[0].text = '关闭'
            this.editDialogInfo.title = '角色详情'
          }
          let roleInfo = await this.Request({
            url: this.api.roleDetail,
            params: {
              roleId: data.roleId,
            },
          })
          this.formData = roleInfo
          if (this.$refs['menu-tree']) {
            this.$refs['menu-tree'].setCheckedKeys(roleInfo.menuIds)
          }
        }
      })
    },
    //删除
    async delRole(e, data) {
      e.stopPropagation()
      this.$confirm(`确定要删除【${data.roleName}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await this.Request({
            url: this.api.delRole,
            params: {
              roleId: data.roleId,
            },
          })
          this.$message.success('删除成功')
          this.loadDataList()
        })
        .catch(() => {})
    },
    checkTree() {
      this.formData.menuIds = this.$refs['menu-tree'].getCheckedKeys()
    },
    async rowClick(row) {
      let roleInfo = await this.Request({
        url: this.api.roleDetail,
        params: {
          roleId: row.roleId,
        },
      })
      this.curRow = row
      this.selectedMenuIds = roleInfo.menuIds
      this.$refs['menu-tree-detail'].setCheckedKeys(roleInfo.menuIds)
    },
    async loadMenu() {
      let menuData = await this.Request({
        url: this.api.loadMenu,
      })
      this.treeData = menuData
    },
    async saveRoleMenu() {
      let menuIdArray = this.$refs['menu-tree-detail'].getCheckedKeys()
      await this.Request({
        url: this.api.saveRoleMenu,
        params: {
          roleId: this.curRow.roleId,
          menuIds: menuIdArray.join(','),
        },
      })
      this.$message.success('保存成功')
    },
    checkTreeMenu() {
      this.selectedMenuIds = this.$refs['menu-tree-detail'].getCheckedKeys()
    },
  },
  created() {
    this.loadMenu()
  },
  beforeCreate() {},
}
</script>
<style lang="less" scoped>
.detail-tree-panel {
  height: calc(~'100vh - 300px');
  overflow: auto;
}
.tree-panel {
  max-height: 400px;
  overflow: auto;
}
</style>
